﻿using CK.Sprite.CrossCutting;
using CK.Sprite.Framework;
using CK.Sprite.ThirdContract;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Authorization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Core
{
    public class FormValidateService : IFormViewValidator
    {
        private SpriteFormLocalCache _spriteFormLocalCache;
        private SpriteViewLocalCache _spriteViewLocalCache;
        public FormValidateService(SpriteFormLocalCache spriteFormLocalCache, SpriteViewLocalCache spriteViewLocalCache)
        {
            _spriteFormLocalCache = spriteFormLocalCache;
            _spriteViewLocalCache = spriteViewLocalCache;
        }

        public bool CheckIsLastVersion(string relationInfos)
        {
            var relationInfoInputs = JsonConvert.DeserializeObject<RelationInfoInputs> (relationInfos);
            if(relationInfoInputs != null && relationInfoInputs.RelationInfos != null)
            {
                var formDatas = _spriteFormLocalCache.GetAllDict(relationInfoInputs.ApplicationCode);
                var viewDatas = _spriteViewLocalCache.GetAllDict(relationInfoInputs.ApplicationCode);
                foreach (var relationInfo in relationInfoInputs.RelationInfos)
                {
                    if(relationInfo.RelationType == 1)
                    {
                        if(!formDatas.ContainsKey(relationInfo.Id) || formDatas[relationInfo.Id].Version != relationInfo.Version)
                        {
                            return false;
                        }
                    }
                    else
                    {
                        if (!viewDatas.ContainsKey(relationInfo.Id) || viewDatas[relationInfo.Id].Version != relationInfo.Version)
                        {
                            return false;
                        }
                    }
                }

                return true;
            }

            return false;
        }
    }
}
